

//排序
$(document).ready(function(){
  $("#sort-repeat").click(function(){
    $("#ordinal").empty();
    $("#dict").empty();
    $("#trans").empty();
    $("#N").val("");

  });
  $("#sort").click(function(){
    $("#ordinal").empty();
    $("#dict").empty();
    $("#trans").empty();
    var N = $("#N").val()*1;

    //ordinal
    for (var i = fac(N)-1; i >= 0; i--) {
      var arr = facToPermutation(toFacNum(i,N),N);
      $("#ordinal").append("<p>" + arr + "</p>");
    }

    //dict
    var dictOrder = [];  //初始序列
    for (var i = 0; i < N; i++) {
      dictOrder[i] = i + 1;
    }
    $("#dict").append("<p>" + dictOrder + "</p>");
    for (var i = 1; i < fac(N); i++) {
      dictOrder = nextDictOrder(dictOrder);
      $("#dict").append("<p>" + dictOrder + "</p>");
    }

    //trans
    var transOrder = []; //初始序列
    var stat = [];
    for (var i = 0; i < N; i++) {
      transOrder[i] = i + 1;
      stat[i] = -1;
    }
    $("#trans").append("<p>" + transOrder + "</p>");
    for (var i = 1; i < fac(N); i++) {
      [transOrder,stat] = nextTransOrder(transOrder,stat);
      $("#trans").append("<p>" + transOrder + "</p>");
    }
  });

  //比较
  var flag = 0;
  var autoFlag = 0;
  var ordinalTimeArray = [];
  var dictTimeArray = [];
  var transTimeArray = [];
  for (var i = 0; i < 20; i++) {
    ordinalTimeArray[i] = [];
    dictTimeArray[i] = [];
    transTimeArray[i] = [];
  }
  $("#compare-repeat").click(function(){
    flag = 0;
    clearInterval(autoFlag);
    $("#compare-auto").html("<i class=\"fa fa-play\" id=\"spin-auto\"></i>自动");
    $("#time-ordinal").empty();
    $("#time-dict").empty();
    $("#time-trans").empty();
    $("input[name='begin-N']").val("");
    $("input[name='end-N']").val("");
    ordinalTimeArray = [];
    dictTimeArray = [];
    transTimeArray = [];
    for (var i = 0; i < 20; i++) {
      ordinalTimeArray[i] = [];
      dictTimeArray[i] = [];
      transTimeArray[i] = [];
    }
  });
  function autoClick() {
    $("#compare").click();
  }

  $("#compare-auto").click(function(){
    if (flag == 0) {
      $("#compare-auto").html("<i class=\"fa fa-pause\" id=\"spin-auto\"></i>暂停");
      flag = 1;
      autoFlag = setInterval(autoClick,2000);
    } else {
      $("#compare-auto").html("<i class=\"fa fa-play\" id=\"spin-auto\"></i>开始");
      flag = 0;
      clearInterval(autoFlag);
    }
  });
  
  $("#compare").click(function(){
   $("#time-ordinal").empty();
   $("#time-dict").empty();
   $("#time-trans").empty();
   $("#time-table").empty();
   $("#op-table").empty();
   
    var beginN = document.forms["form-compare"]["begin-N"].value*1;
    var endN = document.forms["form-compare"]["end-N"].value*1;
    //ordinal
    $.get("/GraduationProject/Arrange",{"beginN":beginN,"endN":endN},function(data,status){
		var obj = JSON.parse(data);
		var xAxisData = [];
		var ordinalData = [];
		var dictData = [];
		var transData = [];
		
		for(var n = beginN;n <= endN;n++){
			xAxisData.push(n);
			ordinalData.push(obj["ordinalTime" + n]);
			dictData.push(obj["dictTime" + n]);
			transData.push(obj["transTime" + n]);
			$("#time-table").append("<tr>" + 
    				"<td>" + n + "</td>" +
    				"<td>" + obj["ordinalTime" + n] + "</td>" +
    				"<td>" + obj["dictTime" + n] + "</td>" +
    				"<td>" + obj["transTime" + n] + "</td>" +
    				"</tr>");
			$("#op-table").append("<tr>" + 
    				"<td>" + n + "</td>" +
    				"<td>" + obj["ordinalOp" + n] + "</td>" +
    				"<td>" + obj["dictOp" + n] + "</td>" +
    				"<td>" + obj["transOp" + n] + "</td>" +
    				"</tr>");
		}
		
		//-------------------chart---------------------------
		var myChart = echarts.init(document.getElementById('chart'));

		// 指定图表的配置项和数据
		option = {
			title : {
				text : '效率分析图',
				subtext : ''
			},
			tooltip : {
				trigger : 'axis'
			},
			legend : {
				data : [ '序数法','字典序法', '换位法' ]
			},
			toolbox : {
				show : true,
				feature : {
					dataZoom : {
						yAxisIndex : 'none'
					},
					dataView : {
						readOnly : false
					},
					magicType : {
						type : [ 'line', 'bar' ]
					},
					restore : {},
					saveAsImage : {}
				}
			},
			xAxis : {
				type : 'category',
				boundaryGap : false,
				data : xAxisData
			},
			yAxis : {
				type : 'value',
				axisLabel : {
					formatter : '{value} ns'
				}
			},
			series : [ {
				name : '序数法',
				type : 'line',
				data : ordinalData,
			},{
				name : '字典序法',
				type : 'line',
				data : dictData,
			}, {
				name : '换位法',
				type : 'line',
				data : transData,
				markPoint : {
					data : [ {
						name : '周最低',
						value : -2,
						xAxis : 1,
						yAxis : -1.5
					} ]
				},
			} ]
		};

		// 使用刚指定的配置项和数据显示图表。
		myChart.setOption(option);
		//-------------------chart-end-----------------------
	});
    /*
    for (var curN = beginN;curN <= endN;curN++) {
    	$.get("/GraduationProject/Arrange",{"curN":curN},function(data,status){
    		var obj = JSON.parse(data);
    		
    		$("#time-ordinal").append("<p id='test'>" + obj.ordinalTime + "</p>");
    		$("#time-dict").append("<p>" + obj.dictTime + "</p>");
    		$("#time-trans").append("<p>" + obj.transTime + "</p>");
    		
    		$("#time-table").append("<tr>" + 
    				"<td>" + tmpN + "</td>" +
    				"<td>" + obj.ordinalTime + "</td>" +
    				"<td>" + obj.dictTime + "</td>" +
    				"<td>" + obj.transTime + "</td>" +
    				"</tr>");
    	});
    }*/

  });
  $(".footer").text(new Date().toLocaleString())
  $("#target-enum").click(function(){
	  $(location).attr("href","enum2.html");
  });
  $("#target-chart").click(function(){
	  $(location).attr("href","chart.html");
  });
  $("#target-eg").click(function(){
	  $(location).attr("href","eg.html");
  });
});

function AvrArray(arr) {
  var total = 0;
  for (var i = 0; i < arr.length; i++) {
    total += arr[i];
  }
  return total/arr.length;
}

function fac(n){
  if (n < 0) {
    alert("请输入一个大于等于0的整数！")
  } else if(n == 0 || n == 1){
    return 1;
  } else {
    return n*fac(n-1);
  }
}

function toFacNum(num,n){
  var arr = new Array(n);
  for (var i = 0; i < n; i++) {
    arr[i] = 0;
  }
  var i = 1;
  var j = 2;
  while (num != 0) {
    var e = num%j;
    var num = parseInt(num/j);
    arr[i] = e;
    i++;
    j++;
  }
  return arr;
}

function facToPermutation(facNum,n) {
  arr = new Array(n);
  pointer = new Array(n);
  for (var i = 0; i < n; i++) {
    arr[i] = 0;
    pointer[i] = i;
  }

  for (var i = n-1; i >= 0; i--) {
    var p = facNum[i];
    var index = pointer[p];
    arr[index] = i + 1;
    while (p < n-1) {
      pointer[p] = pointer[p+1];
      p++;
    }
  }
  return arr;
}


function nextDictOrder(arr){
  var m,n = 0;
  for (var i = 1; i < arr.length; i++) {
    if (arr[i-1] < arr[i]) {
      m = i;
    }
  }
  for (var i = m; i < arr.length; i++) {
    if (arr[m-1] < arr[i]) {
      n = i;
    }
  }

  var tmp = arr[m-1];
  arr[m-1] = arr[n];
  arr[n] = tmp;

  for (var i = m,len = arr.length-1; i < parseInt((m+arr.length)/2); i++) {
    [arr[i],arr[len]] = [arr[len],arr[i]];
    len--;
  }

  return arr;
}

function nextTransOrder(arr,stat){
  var maxIndex,maxNum = 0;
  for (var i = 0; i < stat.length; i++) {
    if(stat[i] == -1 && i != 0 && arr[i] > arr[i-1] && arr[i] > maxNum){
      maxNum = arr[i];
      maxIndex = i;
    } else if (stat[i] == 1 && i != arr.length-1 && arr[i] > arr[i+1] && arr[i] > maxNum) {
      maxNum = arr[i];
      maxIndex = i;
    }
  }

  if (maxNum != 0) {
    if (stat[maxIndex] == -1) {
      [arr[maxIndex],arr[maxIndex-1]] = [arr[maxIndex-1],arr[maxIndex]];
      [stat[maxIndex],stat[maxIndex-1]] = [stat[maxIndex-1],stat[maxIndex]];
    } else if (stat[maxIndex] == 1) {
      [arr[maxIndex],arr[maxIndex+1]] = [arr[maxIndex+1],arr[maxIndex]];
      [stat[maxIndex],stat[maxIndex+1]] = [stat[maxIndex+1],stat[maxIndex]];
    }

    for (var i = 0; i < arr.length; i++) {
      if (arr[i] > maxNum) {
        stat[i] = -stat[i];
      }
    }
  }

  return [arr,stat];
}
